package com.qhgrain.app.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.Position;
import com.qhgrain.gway.util.HttpUtil;

@Controller
@RequestMapping("/position")
public class PositionController {

	private static Logger LOG = LoggerFactory.getLogger(PositionController.class);
	private static final String SERVICEURL = ConfigUtil.getProperties(UrlEnum.POSITION);

	

	/**
	 * 根据ID删除岗位
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/deleteByIds")
	@ResponseBody
	public JSONObject deleteByIds(Model model,  String ids,  String status) {

		JSONObject result = new JSONObject();
		if (StringUtil.isBlank(ids) || StringUtil.isBlank(status)) {
			result.put("code", "fail");
			result.put("msg", "岗位id和状态不能为空");
		} else {

			try {
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("ids", ids);
				
				paramMap.put("status", status);
				String vo = HttpUtil.post(SERVICEURL+ "/position/deletePosition",
						paramMap);
				JSONObject voJson = JSONObject.parseObject(vo);
				if ("200".equals(voJson.getString("state"))) {
					result.put("code", "success");
					result.put("msg", "成功");
				} else {
					result.put("code", "fail");
					result.put("msg", "系统出错，删除失败!");
					LOG.error("删除岗位,api失败..."+ voJson.getString("exceptionMsg"));
				}
			} catch (Exception e) {
				LOG.error("删除岗位，系统出错...." ,e);
				result.put("code", "fail");
				result.put("msg", "系统出错");
			}
		}

		return result;
	}

	/**
	 * 获取所有岗位
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String queryPositions(Model model, String pageNo, String pageSize,
			Position position) {

		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtil.isNotBlank(position.getPostName())) {
			map.put("postName", position.getPostName().trim());
			model.addAttribute("postName", position.getPostName().trim());
		}
		if (StringUtil.isNotBlank(position.getPostOrder())) {
			map.put("postOrder", position.getPostOrder().trim());
			model.addAttribute("postOrder", position.getPostOrder().trim());
		}
		if (StringUtil.isNotBlank(position.getUnitId())) {
			map.put("unitId", position.getUnitId().trim());
			model.addAttribute("unitId", position.getUnitId().trim());
		}
		if (StringUtil.isNotBlank(position.getUnitName())) {
			map.put("unitName", position.getUnitName().trim());
			model.addAttribute("unitName", position.getUnitName().trim());
		}
		if (StringUtil.isNotBlank(position.getDescription())) {
			map.put("description", position.getDescription().trim());
			model.addAttribute("description", position.getDescription().trim());
		}
		
		String status = position.getStatus();
		if (StringUtil.isNotBlank(status)) {
			map.put("status", status.trim());
			model.addAttribute("status", status.trim());
		}
		map.put("pageNum", pageNo);
		map.put("pageSize", pageSize);
		String requestVo;
		try {
			requestVo = HttpUtil.postFormParams(SERVICEURL, "/position/selectPosition", map);
			JSONObject voJson = JSONObject.parseObject(requestVo);

			if ("200".equals(voJson.getString("state"))) {
				JSONArray list = voJson.getJSONArray("data");
			

				PageBean<Object> pageBean = new PageBean<Object>(
						Integer.parseInt(pageNo), Integer.parseInt(pageSize));
				pageBean.setData(list);
				int count =voJson.getInteger("exceptionMsg");
				pageBean.setTotalCount(count);
				pageBean.setCurrentPage(new Integer(pageNo));
				model.addAttribute("pageBean", pageBean);
				return "position/position_list";
			} else {
				LOG.error("岗位查询,api出错。。。。" );
			}

		} catch (IOException e) {
			LOG.error("岗位查询出错。。。。" + e.getStackTrace());
		}

		return "position/list";
	}

	/**
	 * 跳转 编辑/修改 岗位页面
	 * 
	 * @param position
	 * @return
	 */
	@RequestMapping(value = "/goEdit")
	public String goEdit( String positionId,String currentPage,String pageSize, Model model) {
		JSONObject position = new JSONObject();
		if (!StringUtil.isBlank(positionId)) {
			Map<String,String> params=new HashMap<String,String>();
			params.put("id", positionId);
			try {
				String jsonstr = HttpUtil.get(SERVICEURL+"/position/getPositionById", params);
				JSONObject voJson = JSONObject.parseObject(jsonstr);
				if ("200".equals(voJson.getString("state"))) {
					position = voJson.getJSONObject("data");

				} else {
					LOG.error("编辑岗位，从api获取对象信息失败..."
							+ voJson.getString("exceptionMsg"));
				}
			} catch (Exception e) {
				LOG.error(e.getMessage());
			}

		}
		model.addAttribute("position", position);
		model.addAttribute("currentPage", currentPage);
		model.addAttribute("pageSize", pageSize);
		return "/position/position_edit";
	}
	/**
	 * 
	 * 2016年3月29日 下午8:09:49  
	 * @tags 保存岗位
	 * @author zhaoyq
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject save(Model model,Position position){
		JSONObject result = new JSONObject();
		try {
			if(position == null ){
				result.put("code", "fail");
				result.put("msg","请确保数据填写完整");
			}else{
				String postName = position.getPostName();
				String description = position.getDescription();
				String postOrder = (StringUtil.isBlank(position.getPostOrder()))?"0":(position.getPostOrder());
				String status = position.getStatus();
				String unitId = position.getUnitId();
				String unitName = position.getUnitName();
				if( StringUtil.isBlank(postName) || StringUtil.isBlank(postName) ){
					result.put("code", "fail");
					result.put("msg","岗位名不能为空");
				}else{
					String vo ;
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("description", description);
					map.put("postName", postName);
					map.put("postOrder", postOrder);
					map.put("status", status);
					map.put("unitId", unitId);
					map.put("unitName", unitName);
					if(StringUtil.isBlank(position.getId())){
						//新增
						vo = HttpUtil.postFormParams(SERVICEURL, "/position/insertPosition", map);
					}else{
						//修改
						map.put("id", position.getId());
						vo = HttpUtil.postFormParams(SERVICEURL, "/position/updatePosition", map);
					}
					JSONObject voJson = JSONObject.parseObject(vo);
					if("200".equals(voJson.getString("state"))){
						result.put("code", "success");
						result.put("msg", "成功");
					}else{
						result.put("code", "fail");
						result.put("msg", "系统出错，操作失败!");
						LOG.error("保存岗位,api失败..."+voJson.getString("exceptionMsg"));
					}
				}
			}
			
		} catch (Exception e) {
			LOG.error("保存岗位系统出错。。。"+e.getMessage());
		}
		return result;
	}

	/**
	 * 根据ID获取岗位
	 * 
	 * @param positionId
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/getPositionById/{positionId}")
	public String getPositionById(@PathVariable String positionId, Model model) throws IOException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("id", positionId);
		String str = HttpUtil.get(SERVICEURL + "/position/getPositionById", params);
		model.addAttribute("position", JSONObject.parseObject(str));
		return "position/position_view";
	}

	

}
